#!/usr/bin/python3
import os
import tkinter
import pyqrcode
import socket
import _thread
import http.server
import windnd
import math
from urllib import parse
import tkinter.filedialog

VERSION = "1.0"
URL = socket.gethostbyname(socket.getfqdn(socket.gethostname()))
PORT = 8000
PATH = ""


class Resquest(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        super().do_GET()

    def translate_path(self, path):
        return PATH


def createHTTPServer():
    global URL, PORT
    server = None
    while(not server):
        try:
            server = http.server.HTTPServer((URL, PORT), Resquest)
        except:
            PORT = PORT + 1

    URL = "http://%s:%s" % (URL, PORT)
    print("listen at: %s" % URL)
    _thread.start_new_thread(lambda server: server.serve_forever(), (server, ))


def runLauncher():
    size = 500
    font = ('Arial', 16)

    # window
    window = tkinter.Tk()
    window.title(u"隔空投送 %s" % VERSION)
    window.geometry('%sx%s' % (size, size+60))

    createHTTPServer()

    # 网址
    url_frame = tkinter.Frame(window)
    url_frame.pack(anchor="w", fill=tkinter.X)
    url_label = tkinter.Label(url_frame, text="网址:", font=font)
    url_label.pack(side=tkinter.LEFT)
    url_text = tkinter.Text(url_frame, font=font, height=1)
    url_text.pack(fill=tkinter.X)

    # 文件路径
    path_frame = tkinter.Frame(window)
    path_frame.pack(anchor="w", fill=tkinter.X)
    path_label = tkinter.Label(path_frame, text="文件路径:", font=font)
    path_label.pack(side=tkinter.LEFT)
    path_text = tkinter.Text(path_frame, font=font, height=1)
    path_text.pack(fill=tkinter.X)

    # 二维码
    code_image = tkinter.BitmapImage(foreground="black", background="white")
    code_label = tkinter.Label(window, image=code_image)
    code_label.pack()

    dragFiles(url_text, path_text, code_image, size, [tkinter.filedialog.askopenfilename()])
    windnd.hook_dropfiles(window, func=lambda files: dragFiles(url_text, path_text, code_image, size, files))

    tkinter.mainloop()


def dragFiles(url_text, path_text, code_image, size, files):
    if len(files) == 0:
        return

    global PATH
    if isinstance(files[0], bytes):
        PATH = files[0].decode('gb2312', errors='ignore')
    else:
        PATH = files[0]
    print(PATH)

    url = "%s/%s" % (URL, parse.quote(os.path.basename(PATH)))
    print(url)
    url_text["state"] = tkinter.NORMAL
    url_text.delete("1.0", tkinter.END)
    url_text.insert("insert", "%s" % url)
    url_text["state"] = tkinter.DISABLED

    path_text["state"] = tkinter.NORMAL
    path_text.delete("1.0", tkinter.END)
    path_text.insert("insert", "%s" % PATH)
    path_text["state"] = tkinter.DISABLED

    code = pyqrcode.create(url)
    code_image.config(data=code.xbm(scale=math.floor(size / code.get_png_size())))


def main():
    runLauncher()


if __name__ == '__main__':
    main()
